package com.csii.test;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import com.csii.test.sm.SM2Utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HttpsToPaygate {

	public static void main(String[] args) {
		
		Map postMap = HttpsToPaygate.getPostData();
		
		try {
            // 创建SSLContext，信任所有证书
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            sslContextBuilder.loadTrustMaterial(null, (chain, authType) -> true);
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                    sslContextBuilder.build(),
                    NoopHostnameVerifier.INSTANCE);

            HttpClient httpClient = HttpClientBuilder.create()
                   .setSSLSocketFactory(sslSocketFactory)
                   .build();

            HttpPost httpPost = new HttpPost((String)postMap.get("url"));

            // 设置请求头相关信息
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/5.0");

            // 设置请求体数据
            StringEntity entity = new StringEntity((String)postMap.get("postData"));
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);

            // 获取响应码
            int responseCode = response.getStatusLine().getStatusCode();
            System.out.println("Response Code : " + responseCode);

            // 读取响应内容
            String responseContent = EntityUtils.toString(response.getEntity());
            System.out.println("Response Content: " + responseContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	public static Map<String, String> getPostData() {

		Map postMap = new HashMap<String, String>();
		String postData ="";

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		final String orderId = "TEST"+sdf.format(new Date())+"991511801";
		String transId = "TYXD";
		String signType = "RSA";

		String sUrl ="https://unionpay.gsrcu.com/QRC/"+transId+".do";	//测试地址
//		String sUrl ="https://unionpay.gsrcu.com/QRC/"+transId+".do";		//生产地址

		try {
			// 构造XML字符串
			String plain = "<Message>\n" +
					"    <TransId>" + transId + "</TransId>\n" +
					"    <MerchantId>95162014214P0X9</MerchantId>\n" +
					"    <OrderId>" + orderId + "</OrderId>\n" +
					"    <Subject>测试subject</Subject>\n" +
					"    <MerTransDateTime>" + sdf.format(new Date()) + "</MerTransDateTime>\n" +
					"    <TransAmount>0.01</TransAmount>\n" +
					"    <TerminalID>5006A03G</TerminalID>\n" +
					"    <MsceneBrandId>M20230531918</MsceneBrandId>\n" +
					"    <ChannelId>06</ChannelId>\n" +
					"    <MerchantIP>192.168.0.104</MerchantIP>\n" +
					"    <areaInfo>1568200</areaInfo>\n" +
					"    <consignee>PMS</consignee>\n" +
					"    <MerchantUrl>\n" +
					"    <url id=\"cvpp6jivtfeul0bpilcg\" type=\"url\" status=\"parsed\" title=\"\" wc=\"25\">https://apicn.comtree.cn/v1/pay/gsSlsPayNotify</url>\n" +
					"    </MerchantUrl>\n" +
					"    <NotifyFlag>N</NotifyFlag>\n" +
					"    <MerchantMac>00-FF-D8-74-74-A0</MerchantMac>\n" +
					"</Message>";
			String signdata = "";
			if(signType.equals("RSA")){
				signdata = Util.signPaygateData(plain);
				System.out.println("Signature="+signdata);
			} else {
				signdata = SM2Utils.encrypt(plain);
			}

			postData = "Plain="+URLEncoder.encode(plain)+"&Signature="+signdata;
			System.out.println("请求数据:"+postData);
			postMap.put("postData", postData);
			postMap.put("url", sUrl);
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return postMap;
	}
}
